#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "http_client.h"

// 响应数据结构
typedef struct {
    char* data;
    size_t size;
} ResponseData;

// CURL写回调函数
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    size_t realsize = size * nmemb;
    ResponseData* mem = (ResponseData*)userp;
    
    char* ptr = realloc(mem->data, mem->size + realsize + 1);
    if(!ptr) {
        return 0;  // 内存分配失败
    }
    
    mem->data = ptr;
    memcpy(&(mem->data[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->data[mem->size] = 0;
    
    return realsize;
}

// 异步GET请求函数
void http_get_async(const char* url, HttpCallback callback) {
    if (!url || !callback) {
        if (callback) callback(NULL, HTTP_ERROR_INVALID_URL);
        return;
    }
    
    CURL* curl;
    CURLcode res;
    ResponseData chunk;
    
    // 初始化响应数据
    chunk.data = malloc(1);
    chunk.size = 0;
    
    if (!chunk.data) {
        callback(NULL, HTTP_ERROR_MEMORY);
        return;
    }
    
    // 初始化CURL
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    
    if(curl) {
        // 设置CURL选项
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk);
        curl_easy_setopt(curl, CURLOPT_USERAGENT, "CRequestLib/1.0");
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
        
        // 执行请求
        res = curl_easy_perform(curl);
        
        // 检查结果
        if(res != CURLE_OK) {
            free(chunk.data);
            callback(NULL, HTTP_ERROR_REQUEST_FAILED);
        } else {
            // 成功，调用回调
            callback(chunk.data, HTTP_SUCCESS);
            free(chunk.data);
        }
        
        // 清理CURL
        curl_easy_cleanup(curl);
    } else {
        free(chunk.data);
        callback(NULL, HTTP_ERROR_NETWORK);
    }
    
    curl_global_cleanup();
}
